package com.terrapages.wmsc4j.client.mosaic.prodcon;

import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.List;

import org.apache.log4j.Logger;

import com.lisasoft.patterns.producerconsumer.Producer;
import com.terrapages.wmsc4j.layer.tile.Tile;

/**
 * Produces Placeable images by requesting tiles from the tilecache.
 * Contains a list of WMS request URLs from which to take and make a request 
 * @author mvivian
 */
public class TileImageProducer extends Producer<PlacableImage> {
	private static Logger log = Logger.getLogger(TileImageProducer.class);
	private List<Pair<Tile,Point>> tileList;
	
	public TileImageProducer(List<Pair<Tile,Point>> tileList) {
		this.tileList = tileList;
	}


	/**
	 * Removes one of the urls and make a request and then gets the image back
	 * which it puts into a PlaceableImage object along with the Point at which
	 * the consumer can paint it onto the big picture.
	 *	@Override
	 * @return PlacableImage
	 */
	protected PlacableImage produce() {
		PlacableImage retImage = null;
		Tile tile = null;
		Point placement = null;
		
		synchronized (tileList) 
		{
			if(!tileList.isEmpty())
			{
				final Pair<Tile,Point> tilePair = tileList.remove(0);
				tile = tilePair.getLeft();
				placement = tilePair.getRight();
			}
		}
		
		if(tile !=null)
		{
			BufferedImage image = null;
			log.debug("Getting tile " + tile + " for image position " + placement);
			tile.getLayer().getTile(tile); //Fetches Image
			image = tile.getImage();
			retImage = new PlacableImage(image,placement);
		}
		return retImage;
	}
}